package com.oceansoft.mobile.biz.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.biz.api.entity.Member;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.util.HttpClientUtil;
import com.oceansoft.mobile.common.util.Result;
import com.oceansoft.mobile.common.util.StringUtils;
import com.oceansoft.mobile.weixin.util.RequestUtils;
import com.oceansoft.mobile.weixin.util.WeixinUtil;

import io.netty.util.internal.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("api/netApprove")
public class ApiNetApproveController {
    //接口URL
    static final String SetLbbaBaseInfo = Constant.host5 + "api/OnlineReport/SetLbbaBaseInfo";//提交基本信息
    static final String Bureau_depts = Constant.host5 + "api/police/Bureau_depts";//获得派出所
    static final String setLbbaNetDept = Constant.host5 + "api/OnlineReport/SetLbbaNetDept";//提交联网单位续表
    static final String setLbbaNetHostRecord = Constant.host5 + "api/OnlineReport/SetLbbaNetHostRecord";//提交主机托管单位续表
    static final String SetLbbaNetSite = Constant.host5 + "api/OnlineReport/SetLbbaNetSite";//提交网站用户备案表
    static final String SetLbbaNetAnnex = Constant.host5 + "api/OnlineReport/SetLbbaNetAnnex";//提交附件信息
    static final String GetLbbaBaseInfon = Constant.host5 + "api/OnlineReport/GetLbbaBaseInfon";//获取基本信息
    static final String GetLbbaNetDept = Constant.host5 + "api/OnlineReport/GetLbbaNetDept";//获取单位续表
    static final String GetLbbaNetHostRecord = Constant.host5 + "api/OnlineReport/GetLbbaNetHostRecord";//获取主机托管单位续表
    static final String GetLbbaNetSite = Constant.host5 + "api/OnlineReport/GetLbbaNetSite";//获取网站用户备案表
    static final String GetLbbaNetAnnex = Constant.host5 + "api/OnlineReport/GetLbbaNetAnnex";//获取附件
    static final String Shenbao = Constant.host5 + "api/Product/Shenbao";//申报数据推送

    //静态变量
    static final String YHXZGR = "个人";
    static final String JSJXXWL = "jsjxxwl";//基本信息
    static final String LWDWXB = "lwdwxb";//联网单位续表
    static final String ZJTGDWXB = "zjtgdwxb";//主机托管单位续表
    static final String WZBADWXB = "wzbadwxb";//网站用户备案表
    //    static final String FJBGR = "fjbgr";
//    static final String FJBDW = "fjbdw";
    static final String NETAPPROVE_FJ = "netapprove_fj";//session中附件名称
    static final int DWFJS = 4;//单位附件数量

    /***
     * 页面跳转
     *
     * @param pageName
     * @return
     */
    @RequestMapping("getPage/{pageName}")
    public String getPage(@PathVariable("pageName") String pageName,HttpServletRequest request, Model model) {
    	String source = (String) request.getSession().getAttribute("source");
	       if (StringUtils.isNotBlank(source)) {
	       	model.addAttribute("source", source);
	       }
        return "weixin/netapprove/" + pageName;
    }

    /***
     * 附带用户信息的页面跳转
     *
     * @param pageName
     * @param sessiion
     * @param request
     * @param model
     * @return
     * @throws IllegalArgumentException
     * @throws IOException
     */
    @RequestMapping(value = "gotoPageWithUser/{pageName}")
    public String gotoPage(@PathVariable("pageName") String pageName, HttpSession sessiion, HttpServletRequest request,
                           Model model) throws IllegalArgumentException, IOException {
        boolean b = WeixinUtil.checkIsLoginUser(request);
        if (!b) {
            model.addAttribute("openId", sessiion.getAttribute("openId"));
            model.addAttribute("gotoPage", "/api/netApprove/gotoPageWithUser/" + pageName);
            return "weixin/login/login";
        } else {
            Member member = (Member) sessiion.getAttribute(Constant.SESSION_USER);
            model.addAttribute("member", member);
            String a = HttpClientUtil.doGet(GetLbbaBaseInfon, "userguid", member.getGuid());
            JSONObject json = JSONObject.parseObject(a);
            if ((Boolean) json.get("succ")) {
                JSONObject data = (JSONObject) json.get("data");
                if (data != null) {
                    //身份证
                    String sfzjhm = (String) data.get("SFZJHM");
                    data.put("ZJLX", sfzjhm.split(",")[0]);
                    data.put("SFZJHM", sfzjhm.split(",")[1]);
                    model.addAttribute("data", data);
                    
                }
            }
            String source = (String) request.getSession().getAttribute("source");
 	       if (StringUtils.isNotBlank(source)) {
 	       	model.addAttribute("source", source);
 	       }
            return "weixin/netapprove/" + pageName;
        }

    }

    /***
     * 提交基本信息
     *
     * @param request
     * @return
     * @throws IllegalArgumentException
     * @throws IOException
     */
    @RequestMapping(value = "submitNetApprove")
    public String NetApprove(HttpServletRequest request, Model model) throws IllegalArgumentException, IOException {
        Map<String, String> params = RequestUtils.buildParamsByNamesFromRequest(request);
        String yhxz = request.getParameter("YHXZ");
        String lwyt = StringUtils.join(request.getParameterValues("LWYT"), "|");
        String ssqy = params.get("SSQY_1") + "|" + params.get("SSQY_2");
        String sfzjhm = params.get("ZJLX") + "," + params.get("SFZJHM");
        params.put("LWYT", lwyt);//联网用途
        params.put("SSQY", ssqy);//所属区域
        params.put("SFZJHM", sfzjhm);//身份证件号码
        params.put("AQGLYZSBH1", "test");//安全管理员证书编号
        String a = HttpClientUtil.doPost(SetLbbaBaseInfo, params, "utf-8");
        System.out.println(a);
        JSONObject json = JSONObject.parseObject(a);
        if ((Boolean) json.get("succ")) {
            JSONObject data = (JSONObject) json.get("data");
            data.put("yhxz", yhxz);//用户性质保存在session的data中
            request.getSession().setAttribute("NetApproveBackData", data);//基本信息提交返回值保存在session中
            return gotoNextPage(request, model, JSJXXWL);
        }
        return "";
    }

    /***
     * 提交联网单位续表
     *
     * @param request
     * @param model
     * @return
     * @throws IllegalArgumentException
     * @throws IOException
     */
    @RequestMapping(value = "submitLwdwxb")
    public String Lwdwxb(HttpServletRequest request, Model model) throws IllegalArgumentException, IOException {
        JSONObject data = (JSONObject) request.getSession().getAttribute("NetApproveBackData");
        String baseGuid = data.getString("BaseGuid");//基本信息ID
        Map<String, String> params = RequestUtils.buildParamsByNamesFromRequest(request);
        String sswl = StringUtils.join(request.getParameterValues("SSWL"), "|");
        String lwdwjrfs = StringUtils.join(request.getParameterValues("LWDWJRFS"), "|");
        String aqcs = StringUtils.join(request.getParameterValues("AQCS"), "|");
        String sjfs = StringUtils.join(request.getParameterValues("SJFS"), "|");
        String ywipdzfw = request.getParameter("YWIPDZFW");
        String ipdzfw = request.getParameter("IPDZFW");
        params.put("SSWL", sswl);//所属网络
        params.put("LWDWJRFS", lwdwjrfs);//联网单位接入方式
        params.put("AQCS", aqcs);//安全措施
        params.put("SJFS", sjfs);//审计方式
        if ("0".equals(ywipdzfw)) {
            params.put("ADSLZH", ipdzfw);//IP地址范围||ADSL上网账号
            params.remove("IPDZFW");
        }
        params.put("NETRECORDID", baseGuid);
        String a = HttpClientUtil.doPost(setLbbaNetDept, params, "utf-8");
        System.out.println(a);
        JSONObject json = JSONObject.parseObject(a);
        if ((Boolean) json.get("succ")) {
            return gotoNextPage(request, model, LWDWXB);
        }
        return "";
    }


    /***
     * 提交主机托管单位续表
     *
     * @param request
     * @param model
     * @return
     * @throws IllegalArgumentException
     * @throws IOException
     */
    @RequestMapping(value = "submitZjtgdwxb")
    public String Zjtgdwxb(HttpServletRequest request, Model model) throws IllegalArgumentException, IOException {
        JSONObject data = (JSONObject) request.getSession().getAttribute("NetApproveBackData");
        String baseGuid = data.getString("BaseGuid");//基本信息ID
        Map<String, String> params = RequestUtils.buildParamsByNamesFromRequest(request);
        String dwxz = StringUtils.join(request.getParameterValues("DWXZ"), "|");
        String jrwlmc = StringUtils.join(request.getParameterValues("JRWLMC"), "|");
        String jyxkzh = request.getParameter("JYXKZH");//经营许可证号
        params.put("DWXZ", dwxz);//单位性质
        params.put("JRWLMC", jrwlmc);//接入网络名称
        //有无经营许可证号
        if (!StringUtil.isNullOrEmpty(jyxkzh)) {
            params.put("YWJYXKZH", "1");
        } else {
            params.put("YWJYXKZH", "0");
        }
        params.put("NETRECORDID", baseGuid);
        String a = HttpClientUtil.doPost(setLbbaNetHostRecord, params, "utf-8");
        System.out.println(a);
        JSONObject json = JSONObject.parseObject(a);
        if ((Boolean) json.get("succ")) {
//            String guid = (String) json.get("data");
            return gotoNextPage(request, model, ZJTGDWXB);
        }
        return "";
    }

    /***
     * 提交网站用户备案表
     *
     * @param request
     * @param model
     * @return
     * @throws IllegalArgumentException
     * @throws IOException
     */
    @RequestMapping(value = "submitWzbadwxb")
    public String Wzbadwxb(HttpServletRequest request, Model model) throws IllegalArgumentException, IOException {
        JSONObject data = (JSONObject) request.getSession().getAttribute("NetApproveBackData");
        String baseGuid = data.getString("BaseGuid");//基本信息ID
        Map<String, String> params = RequestUtils.buildParamsByNamesFromRequest(request);
        String tghlwfwlx = StringUtils.join(request.getParameterValues("TGHLWFWLX"), "|");
        String jrfs = StringUtils.join(request.getParameterValues("JRFS"), "|");
        params.put("TGHLWFWLX", tghlwfwlx);//提供互联网服务所有类型
        params.put("JRFS", jrfs);//接入方式
        params.put("NETRECORDID", baseGuid);

        JSONObject object = new JSONObject();
        object.putAll(params);
        JSONObject paraJson = new JSONObject();
        paraJson.put("SITEGUID", request.getParameter("SITEGUID"));
        paraJson.put("SiteInfo", object);

        String a = HttpClientUtil.doPostString(SetLbbaNetSite, paraJson);
        System.out.println(paraJson.toJSONString());
        System.out.println(a);
        JSONObject json = JSONObject.parseObject(a);
        if ((Boolean) json.get("succ")) {
//            String guid = (String) json.get("data");
            return gotoNextPage(request, model, WZBADWXB);
        }
        return "";
    }


    /***
     * 附件上传
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "uploadFile", method = RequestMethod.POST)
    public Result uploadFile(MultipartHttpServletRequest request) {
        String materialname = request.getParameter("materialname");
        String type = request.getParameter("type");
        //type字段用于识别前台传过来的不同图片
        Result result = RequestUtils.saveFj(request, "file", type, false);
        Map<String, Result> m = (Map<String, Result>) request.getSession().getAttribute(NETAPPROVE_FJ);
        if (null == m) {
            m = new HashMap<String, Result>();
        }
        JSONObject data = (JSONObject) result.getData();
        data.put("materialname", materialname);
        data.put("sortid", type);
        result.setData(data);
        m.put(NETAPPROVE_FJ + type, result);
        request.getSession().setAttribute(NETAPPROVE_FJ, m);
//        return new Result(Result.SUCC, "上传成功");
        return result;
    }


    /***
     * 附件列表提交
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "submitNetApproveFiles", method = RequestMethod.POST)
    public Result submitNetApproveFiles(HttpServletRequest request) {
        JSONObject data = (JSONObject) request.getSession().getAttribute("NetApproveBackData");
        String baseGuid = data.getString("BaseGuid");//基本信息ID
        String IsNetHostRecord = data.getString("IsNetHostRecord");//主机托管单位续表状态
        String yhxz = data.getString("yhxz");//用户性质
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("baseguid", baseGuid);
        //获取附件id
        Map<String, Result> m = (Map<String, Result>) request.getSession().getAttribute(NETAPPROVE_FJ);
        request.getSession().removeAttribute(NETAPPROVE_FJ);
        if (null == m || m.isEmpty()) {
            return new Result(false, "请先上传附件");
        }
        if (!YHXZGR.equals(yhxz) ) {
            if("-1".equals(IsNetHostRecord)){
                if( m.size() < (DWFJS - 1)){
                    return new Result(false, "请上传全部附件");
                }
            }else if(m.size() < DWFJS){
                return new Result(false, "请上传全部附件");
            }
        }
        //循环读取附件
        JSONArray array = new JSONArray();
        Set<String> fjkeys = m.keySet();
        for (String key : fjkeys) {
            JSONObject object = new JSONObject();
            Result r = m.get(key);
            object.put("lguid", ((JSONObject) r.getData()).get("prjMatGuid").toString());
            object.put("projectmaterialname", ((JSONObject) r.getData()).get("materialname").toString());
            object.put("sortid", ((JSONObject) r.getData()).get("sortid").toString());
            object.put("ishave", "1");
            array.add(object);
        }
        jsonParam.put("INFOLIST", array);
        Result result = JSONObject.parseObject(HttpClientUtil.doPostString(SetLbbaNetAnnex, jsonParam), Result.class);
        //附件列表提交成功后直接申报
        if (result.isSucc()) {
            return SubmitDeclare(request);
        }
        return result;
    }


    /***
     * 申报
     *
     * @param request
     */
    private Result SubmitDeclare(HttpServletRequest request) {
        JSONObject jsonParam = new JSONObject();
        JSONObject data = (JSONObject) request.getSession().getAttribute("NetApproveBackData");
        String baseGuid = data.getString("BaseGuid");//基本信息ID
        jsonParam.put("declareCaseGuid", "e8e5deb1-232f-4e39-bec5-f7b9b31b2984");//事项guid
        jsonParam.put("matLifo_att", "");//附件材料信息
        jsonParam.put("matLifo_paper", "");//纸质材料信息
        jsonParam.put("LbbaBaseGuid", baseGuid);//联保备案基本信息ID
        RequestUtils.putUser4json(request, jsonParam);//填入用户信息
        Result result = JSONObject.parseObject(HttpClientUtil.doPostString(Shenbao, jsonParam), Result.class);
        return result;
    }


    /***
     * 获取所在区域派出所
     *
     * @param request
     * @return
     * @throws IllegalArgumentException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "getBureau_depts")
    public Result getBureau_depts(HttpServletRequest request) throws IllegalArgumentException, IOException {
        String guid = request.getParameter("guid");
        String a = HttpClientUtil.doGet(Bureau_depts, "guid", guid);
        JSONObject json = JSONObject.parseObject(a);
        Result re = new Result();
        if ((Boolean) json.get("succ")) {
            re.setSucc(Result.SUCC);
            re.setMsg(json.get("msg").toString());
            re.setData(json.get("data"));
        } else {
            re.setSucc(Result.FAILURE);
            re.setMsg(json.get("msg").toString());
        }
        return re;
    }

    /***
     * 根据session中的主表返回值信息和当前页面
     * 判断下一步页面
     *
     * @param request
     * @param model
     * @param thisPage
     * @return
     */
    private String gotoNextPage(HttpServletRequest request, Model model, String thisPage) throws IOException {
        //网站备案续表序号
        String wzIndexStr = request.getParameter("wzIndex");
        int wzIndex = 0;
        if (StringUtils.isNotEmpty(wzIndexStr)) {
            wzIndex = Integer.parseInt(wzIndexStr);
        }
        JSONObject data = (JSONObject) request.getSession().getAttribute("NetApproveBackData");
        String baseGuid = data.getString("BaseGuid");//基本信息ID
        String IsNetDept = data.getString("IsNetDept");//单位续表状态
        String IsNetHostRecord = data.getString("IsNetHostRecord");//主机托管单位续表状态
        JSONArray IsNetSite = (JSONArray) data.get("IsNetSite");//网站用户备案表状态
        JSONArray IsAnnex = (JSONArray) data.get("IsAnnex");//附件状态
        String yhxz = data.getString("yhxz");
        String source = (String) request.getSession().getAttribute("source");
	       if (StringUtils.isNotBlank(source)) {
	       	model.addAttribute("source", source);
	       }
        if (JSJXXWL.equals(thisPage) && ("0".equals(IsNetDept) || "1".equals(IsNetDept))) {
            getPageData(model, GetLbbaNetDept, baseGuid);
            return "weixin/netapprove/lwdwxb";//联网单位续表
        } else if ((LWDWXB.equals(thisPage) || JSJXXWL.equals(thisPage)) && ("0".equals(IsNetHostRecord) || "1".equals(IsNetHostRecord))) {
            getPageData(model, GetLbbaNetHostRecord, baseGuid);
            return "weixin/netapprove/zjtgdwxb";//主机托管单位续表
        } else if ((LWDWXB.equals(thisPage) || JSJXXWL.equals(thisPage) || ZJTGDWXB.equals(thisPage) || WZBADWXB.equals(thisPage)) && IsNetSite.size() > wzIndex) {
            JSONObject object = IsNetSite.getJSONObject(wzIndex);
            String siteState = object.get("SiteState").toString();
            if ("1".equals(siteState)) {
                String siteGuid = object.get("SiteGuid").toString();
                getPageData(model, GetLbbaNetSite, siteGuid);
            }
            model.addAttribute("wzIndex", wzIndex + 1);
            return "weixin/netapprove/wzbadwxb";//网站备案续表
        } else if ((LWDWXB.equals(thisPage) || JSJXXWL.equals(thisPage) || ZJTGDWXB.equals(thisPage) || WZBADWXB.equals(thisPage)) && YHXZGR.equals(yhxz)) {
            getFileList(request, baseGuid);
            return "weixin/netapprove/fjbgr";//个人附件表
        } else {
            getFileList(request, baseGuid);
            model.addAttribute("IsNetHostRecord", IsNetHostRecord);
            
            return "weixin/netapprove/fjbdw";//单位附件表
        }
    }

    /***
     * 调用接口获得相应页面的回填值
     *
     * @param model
     * @param url
     * @param guid
     * @throws IOException
     */
    private void getPageData(Model model, String url, String guid) throws IOException {
        String a = HttpClientUtil.doGet(url, "GUID", guid);
        JSONObject json = JSONObject.parseObject(a);
        if ((Boolean) json.get("succ")) {
            JSONObject data = (JSONObject) json.get("data");
            model.addAttribute("data", data);
        }
    }

    /***
     * 获取附件列表保存到session中
     * 供提交使用
     *
     * @param request
     * @param guid
     * @throws IOException
     */
    private void getFileList(HttpServletRequest request, String guid) throws IOException {
        String a = HttpClientUtil.doGet(GetLbbaNetAnnex, "GUID", guid);
        JSONObject json = JSONObject.parseObject(a);
        if ((Boolean) json.get("succ")) {
            JSONObject data = (JSONObject) json.get("data");
            JSONArray array = data.getJSONArray("MATERIAL");
            Map<String, Result> m = (Map<String, Result>) request.getSession().getAttribute(NETAPPROVE_FJ);
            if (null == m) {
                m = new HashMap<String, Result>();
            }
            for (int i = 0; i < array.size(); i++) {
                JSONObject object = array.getJSONObject(i);
                Result result = new Result();
                JSONObject jsonData = new JSONObject();
                jsonData.put("materialname", object.get("PROJECTMATERIALNAME"));
                jsonData.put("prjMatGuid", object.get("LGUID"));
                jsonData.put("sortid", object.get("SORTID"));
                result.setData(jsonData);
                m.put(NETAPPROVE_FJ + object.get("SORTID"), result);
            }
            request.getSession().setAttribute(NETAPPROVE_FJ, m);
        }
    }
}
